<template>
  <div class="formBox formBox2 mt-15">
    <el-form
      :model="formData"
      :rules="formData.enterpriseType === 1? cultivateFormRules : formRules"
      inline
      ref="ruleForm"
      label-width="150px"
      class="demo-ruleForm"
    >
      <div class="form-tit">基础信息</div>
      <el-form-item label="企业名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入企业名称"
          :disabled="isDisabled"
          maxlength="100"
        ></el-input>
      </el-form-item>
      <el-form-item label="企业类型" prop="enterpriseType">
        <el-select v-model="formData.enterpriseType" placeholder="请选择企业类型" :disabled="isDisabled" @change="handleBusinessEntity">
          <el-option v-for="item in businessEntityOptions" :key="item.label" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="principal">
        <el-input v-model="formData.principal" placeholder="请输入负责人" :disabled="isDisabled" maxlength="100" />
      </el-form-item>
      <el-form-item label="联系电话" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入联系电话" :disabled="isDisabled" maxlength="11" />
      </el-form-item>
      <el-form-item label="所属地区" prop="areaName">
        <el-cascader
          v-model="formData.areaName"
          :options="addressOptions"
          placeholder="请选择所属地区"
          :disabled="isDisabled"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input type="textarea" v-model="formData.address" placeholder="请输入详细地址" :disabled="isDisabled" maxlength="100" />
      </el-form-item>
      <el-form-item label="成立日期" prop="establishedTime">
        <el-date-picker v-model="formData.establishedTime" type="date" placeholder="选择成立日期" :disabled="isDisabled" value-format="yyyy-MM-dd" style="width:300px" />
      </el-form-item>
      <el-form-item label="展示经度" prop="longitude">
        <el-input v-model="formData.longitude" placeholder="请输入展示经度" :disabled="isDisabled" maxlength="11" />
      </el-form-item>
      <el-form-item label="展示纬度" prop="latitude">
        <el-input v-model="formData.latitude" placeholder="请输入展示纬度" :disabled="isDisabled" maxlength="11" />
      </el-form-item>
      <el-form-item label="规模（万羽）" prop="model" v-if="formData.enterpriseType === 1">
        <el-input type="number" v-model="formData.businessScale" placeholder="请输入养殖规模" />
      </el-form-item>
      <el-form-item label="是否溯源认证禽场" prop="isAuthField" v-if="formData.enterpriseType === 1">
        <el-radio-group v-model="formData.isAuthField">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否数字禽场" prop="isDataField" v-if="formData.enterpriseType === 1">
        <el-radio-group v-model="formData.isDataField">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="溯源认证日期" prop="authDate" v-if="formData.isAuthField === 1">
        <el-date-picker v-model="formData.authDate" placeholder="选择溯源认证日期" :disabled="isDisabled" value-format="yyyy-MM-dd" style="width:300px" />
      </el-form-item>

      <div class="form-tit">
        证照信息
        <span class="remind">（点击上传图片，推荐大小为200*200；上传图片不超过3M，格式为jpg、jpeg、png）</span>
      </div>
      <template>
        <el-form-item
          :label="item.label"
          :prop="item.value"
          class="upload-pic"
          v-for="(item,index) in imgList"
          :key="index"
        >
          <el-input v-model="formData[item.value]" style="display: none;"></el-input>
          <div v-if="isDisabled&&formData[item.value]" class="preview-img">
            <el-image
              :src="formData[item.value]"
              class="avatar"
              :preview-src-list="[formData[item.value]]"
            />
          </div>
          <el-upload
            v-else
            :disabled="isDisabled"
            class="avatar-uploader"
            :headers="headers"
            :action="action"
            :show-file-list="false"
            :on-success="handleImgSuccess"
            :before-upload="beforeImgUpload"
          >
            <img
              v-if="formData[item.value]&&formData[item.value] !==' '"
              :src="formData[item.value]"
              class="avatar"
              @click="setImgName(item.value)"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon" @click="setImgName(item.value)"></i>
            <i
              v-if="formData[item.value]&&!isDisabled&&formData[item.value] !==' '"
              class="el-icon-remove"
              @click.stop="remove(item.value)"
            ></i>
          </el-upload>
        </el-form-item>
      </template>
      <!--  -->
    </el-form>
    <div style="text-align: center;padding:20px 0">
      <el-button @click="goBack">返回</el-button>
      <el-button v-if="type!=='view'" type="primary" @click="handelsubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { closeSelectedTag } from '@/utils/index'
import { REG, TEXT_MESSAGE } from '@/utils/verification'
export default {
  name: 'dataForm',
  props: {
    isAdd: {
      type: Boolean
    }
  },
  data () {
    const commonFormRules = {
      name: [
        { required: true, message: '请输入企业名称', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在20个字符以内', trigger: 'blur' }
      ],
      principal: [
        { required: true, message: '请输入负责人', trigger: 'blur' },
        { min: 1, max: 10, message: '长度在10个字符以内', trigger: 'blur' }
      ],
      areaName: [ { required: true, message: '请选择所属地区', trigger: 'change' } ],
      address: [
        { required: true, message: '请输入详细地址', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在20个字符以内', trigger: 'blur' }
      ],
      establishedTime: [{ required: true, message: '请选择成立日期', trigger: 'blur' }],
      enterpriseType: [ { required: true, message: '请选择企业类型', trigger: 'change' }],
      mobile: [{ required: true, message: '请输入联系电话', trigger: 'change' }],
    };
    return {
      imgList: [
        { label: '企业图片', value: 'pictureUrl' },
        { label: '营业执照', value: 'businessLicenseUrl' },
        { label: '经营许可证', value: 'businessPermitUrl' },
        { label: '企业防疫条件合格证', value: 'certificateUrl' },
      ],
      imgName: '',
      type: this.$route.query.type,
      enterpriseId: this.$route.query.id,
      isDisabled: this.$route.query.type === 'view' ? true : false,
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now();
        },
      },
      isLoading: false,
      addressOptions: [
        {
          value: '崇仁县',
          label: '崇仁县',
          children: [
            { value: '六家桥乡', label: '六家桥乡' },
            { value: '巴山镇', label: '巴山镇' },
            { value: '桃源乡', label: '桃源乡' },
            { value: '河上镇', label: '河上镇' },
            { value: '白陂乡', label: '白陂乡' },
            { value: '相山镇', label: '相山镇' },
            { value: '石庄乡', label: '石庄乡' },
            { value: '礼陂镇', label: '礼陂镇' },
            { value: '航埠镇', label: '航埠镇' },
            { value: '许坊乡', label: '许坊乡' },
            { value: '郭圩乡', label: '郭圩乡' },
            { value: '马鞍镇', label: '马鞍镇' },
            { value: '孙坊镇', label: '孙坊镇' },
            { value: '三山乡', label: '三山乡' },
            { value: '白鹭乡', label: '白鹭乡' },
          ]
        }
      ],
      businessEntityOptions: [ //企业类型
        { value: 0, label: '孵化场' },
        { value: 1, label: '规模养殖场' },
        { value: 2, label: '饲料厂' },
        { value: 3, label: '屠宰场' },
        { value: 4, label: '食品加工厂' },
        { value: 5, label: '育种场' },
        { value: 6, label: '销售网点' },
        { value: 7, label: '其他企业' },
      ],
      formData: {
        projectId: 1,
        pictureUrl: '', //企业图片
        businessLicenseUrl: '', //营业执照
        businessPermitUrl: '', //经营许可证
        certificateUrl: '',  //动物防疫条件合格证
      },
      formRules: {
        ...commonFormRules,
      },
      cultivateFormRules: {
        ...commonFormRules,
        isAuthField:[{required: true, message: '请选择认证禽场',}],
        isDataField:[{required: true, message: '请选择是否数字禽场',}]
      },
      action: process.env.VUE_APP_BASE_API + 'xhc/upload?action=uploadimage',
      headers: {
        Authorization: localStorage.token
      },
    };
  },
  mounted () {
    if (this.type !== 'add') {
      this.getEnterpriseInfo();
    }
  },
  methods: {
    getEnterpriseInfo () {
      this.$api.data.getEnterpriseInfo({
        enterpriseId: this.enterpriseId
      }).then(res => {
        this.formData = res.data || {};
        this.formData.areaName = this.formData.areaName.split('/');
      }).catch(() => {
      })
    },
    async handelsubmit () {
      const validateRes = await this.$refs.ruleForm.validate().catch(err => false);
      if (!validateRes) return;

      let params = Object.assign({}, this.formData);
      params.areaName = params.areaName.join('/');
      const res = await this.$api.data.saveEnterpriseInfo(params)
      this.$message.success(this.isAdd? '新增养殖企业成功' : '编辑养殖企业成功')
      this.goBack()
    },
    goBack () {
      this.$bus.$emit('refreshDataList')
      closeSelectedTag(this.$route, '/dataManage/index')
    },
    setImgName (name) {
      this.imgName = name
    },
    handleImgSuccess (res, file) {
      // this.formData.pictureUrl = res.data
      this.formData[this.imgName] = res.data
      this.$forceUpdate();
    },
    remove (name) {
      // this.formData.pictureUrl = '';
      this.formData[name] = ' '
      this.$forceUpdate();
    },
    beforeImgUpload (file) {
      const isJPG = ['image/jpg', 'image/jpeg', 'image/png'].indexOf(file.type);
      const isLt2M = file.size / 1024 / 1024 < 3;

      if (isJPG < 0) {
        this.$message.error('上传头像图片只能是 JPG、JPEG、PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 3MB!');
        return false;
      }
      return isJPG && isLt2M;
    },
    handleBusinessEntity () {
      this.$nextTick( () => {
        this.$refs.ruleForm.clearValidate()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-textarea {
  line-height: 20px;
}
</style>
